<template>
  <a-modal
    :title="modalTitle"
    :width="1100"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" style="max-height: 500px;overflow-y: auto;overflow-x: hidden;">
        <a-form-item label="业务ID" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
          <a-input v-if="modalOpera==1" v-decorator="['id', {rules: [{required: true}]}]" />
        </a-form-item>

        <p>
          分类扩展名称
          <a-icon type="right" />
        </p>
        <a-row :gutter="6" >
          <a-col :xl="{span: 8}" :lg="{span: 8}" :md="{span: 12}">
            <a-form-item label="扩展名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['categoryExtendName', {rules: [{required: true, min: 2, message: '请输入至少二个字符的规则！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider dashed />
        <p>
          扩展字段
          <a-icon type="right" />
        </p>
        <div class="table-operator">
          <a-button style="margin-bottom: 5px;" type="primary" icon="plus" v-has="{perm:'role:save'}" @click="handleAddExtendsField">添加字段</a-button>
          <span style="font-size:12px"> PS:内容扩展字段(source,sourceUrl,text)不可用增加行</span>
        </div>
        <a-table
          bordered
          :pagination="false"
          ref="table"
          rowKey="id"
          :columns="columns"
          size="small"
          :dataSource="dataSource">
          <template v-for="col in extendsField" :slot="col.name" slot-scope="text, record, index">
            <a-form-item :key="col.name" style="padding:0;margin:0">
              <a-input-number
                v-if="col.type === 'number' "
                :min="0"
                v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                @change="e => handleChange(e, record.id, col.name, index,col.type)" />
              <a-input
                v-if="col.type === 'text' "
                :min="0"
                v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                @change="e => handleChange(e, record.id, col.name, index,col.type)" />

              <a-radio
                v-if="col.type === 'radio' "
                v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                @change="e => handleChange(e, record.id, col.name, index,col.type)">
              </a-radio>

              <a-checkbox
                v-if="col.type === 'checkbox' "
                :checked="text"
                v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                @change="e => handleChange(e, record.id, col.name, index,col.type)">
              </a-checkbox>

              <a-textarea
                v-if="col.type === 'textarea' "
                :rows="1"
                v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: col.required, message: '不能为空' }],
                   initialValue:text, validateTrigger: 'change'}
                ]"
                @change="e => handleChange(e, record.id, col.name, index,col.type)">
              </a-textarea>

              <a-select
                v-if="col.type === 'select'"
                :options="inputType"
                v-decorator="[
                  `${col.name}-${index}`,
                  {rules: [{ required: true, message: '不能为空' }],
                   initialValue:text,validateTrigger: 'change'}
                ]"
                @change="e => handleChange(e, record.id, col.name, index,col.type)"></a-select>
            </a-form-item>
          </template>
          <span slot="action" slot-scope="text, record, index">
            <template>
              <a-popconfirm title="确定要删除该明细吗？" @confirm="handleDeleteExtendsField(record, index)" okText="确认" cancelText="取消">
                <a href="#">删除</a>
              </a-popconfirm>
            </template>
          </span>
        </a-table>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {
  save,
  getById,
  update
} from '@/api/cms/category/extend'
import pick from 'lodash.pick'
export default {
  data () {
    return {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 13
        }
      },
      modalTitle: '',
      modalOpera: 0, // 0：新增 1：编辑
      visible: false,
      confirmLoading: false,
      moptions: [],
      dataSource: [],
      inputType: [],
      form: this.$form.createForm(this),
      extendsField: [{
        name: 'code',
        type: 'text',
        required: true
      },
      {
        name: 'inputType',
        type: 'select',
        required: true
      }, {
        name: 'name',
        type: 'text',
        required: true
      },
      {
        name: 'isRequired',
        type: 'checkbox',
        required: true
      },
      {
        name: 'isSearch',
        type: 'checkbox',
        required: true
      },
      {
        name: 'defaultValue',
        type: 'text',
        required: false
      },
      {
        name: 'maxlength',
        type: 'number',
        required: false
      },
      {
        name: 'description',
        type: 'textarea',
        required: false
      },
      {
        name: 'sort',
        type: 'number',
        required: true
      }
      ],
      // 表头
      columns: [{
        title: '编码',
        dataIndex: 'code',
        align: 'center',
        width: '140px',
        scopedSlots: {
          customRender: 'code'
        }
      }, {
        title: '字段类型',
        dataIndex: 'inputType',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'inputType'
        }
      }, {
        title: '名称',
        dataIndex: 'name',
        align: 'center',
        width: '120px',
        scopedSlots: {
          customRender: 'name'
        }
      }, {
        title: '必填',
        dataIndex: 'isRequired',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'isRequired'
        }
      },
      {
        title: '可搜索',
        dataIndex: 'isSearch',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'isSearch'
        }
      }, {
        title: '默认值',
        dataIndex: 'defaultValue',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'defaultValue'
        }
      },
      {
        title: '最大长度',
        dataIndex: 'maxlength',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'maxlength'
        }
      },
      {
        title: '描述',
        dataIndex: 'description',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'description'
        }
      }, {
        title: '排序',
        dataIndex: 'sort',
        align: 'center',
        width: '100px',
        scopedSlots: {
          customRender: 'sort'
        }
      }, {
        title: '操作',
        dataIndex: 'action',
        align: 'center',
        width: '80px',
        scopedSlots: {
          customRender: 'action'
        }
      }
      ]
    }
  },
  created () {
    this.selectInputType()
  },
  methods: {
    add () {
      this.modal('新建分类扩展', 0)
    },
    edit (record) {
      this.modal('编辑分类扩展', 1)
      getById({
        id: record.id
      }).then(response => {
        const result = response.res
        this.form.setFieldsValue(pick(result, 'id', 'categoryExtendName'))
        if (result.extendFieldList) {
          this.setDataSource(JSON.parse(result.extendFieldList))
        }
      })
    },
    modal (title, opera) {
      this.modalTitle = title
      this.modalOpera = opera
      this.visible = true
	  this.clearDataSource()
      this.form.resetFields()
    },
    handleSubmit () {
      const {
        form: {
          validateFields
        }
      } = this
      // this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
		  const param = this.bulidData(values)
		  this.confirmLoading = true
		  console.log(param)
          if (this.modalOpera === 0) {
            save(param).then(response => {
              if(response.code===0){
                this.$message.info(response.msg)
                this.$emit('ok')
                this.handleCancel()
              }else{
                 this.$message.error(response.msg)
              }
             
            })
          } else if (this.modalOpera === 1) {
            update(param).then(response => {
              if(response.code===0){
                this.$message.info(response.msg)
                this.$emit('ok')
                this.handleCancel()
              }else{
                 this.$message.error(response.msg)
              }
            })
          }
        }
        this.confirmLoading = false
      })
    },
    bulidData (values) {
      const param = {
	    id: values.id,
        categoryExtendName: values.categoryExtendName,
        extendFieldList: JSON.stringify(this.dataSource)
      }
      return param
    },
    handleCancel () {
	  this.moptions = []
	  this.checkDefaultFields = []
      this.visible = false
      this.confirmLoading = false
    },
    handleAddExtendsField () {
      const newData = {
        code: '',
        inputType: this.inputType[0].value,
        name: '',
        isRequired: false,
        isSearch: false,
        defaultValue: '',
        maxlength: '',
        description: '',
        sort: 0,
        id: Date.now()
      }
      this.dataSource = [...this.dataSource, newData]
    },
    handleDeleteExtendsField (record, index) {
      this.dataSource.splice(index, 1)
    },
    setDataSource (data) {
      this.dataSource = data
    },
    clearDataSource () {
      this.dataSource = []
    },
    handleChange (e, key, column, index, inputType) {
      const newData = [...this.dataSource]
      const target = newData.filter(item => key === item.id)[0]
      if (target) {
        if (inputType === 'checkbox') {
			 target[column] = e.target.checked
        } else {
			 target[column] = (e instanceof Object) ? e.target.value : e
        }
      }
	  console.log(this.dataSource)
    },
    selectInputType () {
      const inputTypes = [{
        value: 'text',
        label: '输入框'
      },{
        value: 'textarea',
        label: '区域框'
      }, {
        value: 'number',
        label: '数字'
      }, {
        value: 'date',
        label: '日期'
      }, {
        value: 'file',
        label: '文件'
      }, {
        value: 'picture',
        label: '图片'
      }]
      this.inputType = inputTypes
    }
  }
}
</script>
